package com.music.muisc.controllers;

import com.music.muisc.dao.ForumRepository;
import com.music.muisc.dao.InteractionRepository;
import com.music.muisc.entity.Forum;
import com.music.muisc.entity.Interaction;
import com.music.muisc.services.ForumService;
import com.music.muisc.services.InteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("interactions")
public class InteractionController {
    @Autowired
    InteractionService interactionService;

    @Autowired
    ForumService forumService;
    @GetMapping
    public String displayInteractions(Model model){
        List<Interaction> interactions = interactionService.getAll();
        model.addAttribute("interactions", interactions);
        return "interactions/list-interactions";
    }
    @GetMapping("/new")
    public String displayInteractionForm(Model model){
        Interaction aInteraction = new Interaction();
        List<Forum> forums = forumService.getAll();
       model.addAttribute("interaction", aInteraction);
       model.addAttribute("allForums", forums);
        return "interactions/new-interaction";
    }
    @PostMapping("/save")
    public String createInteraction(Model model, @RequestParam List<Long> forums, Interaction interaction){
        //处理保存到数据库的行为
        interactionService.save(interaction);


        //使用重定位防止重复提交
        return "redirect:/interactions";

    }
    @GetMapping("/update")
    public String displayInteractionUpdateForm(@RequestParam("id") int theId, Model model) {
        Interaction theInteraction = interactionService.findByInteractionId(theId);
        model.addAttribute("interaction", theInteraction);

        return "interactions/new-interaction";
    }
    @GetMapping("/delete")
    public String deleteInteraction(@RequestParam("id") int theId, Model model){
        Interaction theInteraction = interactionService.findByInteractionId(theId);
        interactionService.delete(theInteraction);
        return "redirect:/interactions";
    }
}
